package open_directory;

import java.io.File;
import java.io.IOException;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

public class OpenDirectoryHandler extends AbstractHandler {
	final static boolean isWindows;
	static {
		String os = System.getProperty("os.name");
		if (os != null) {
			isWindows = os.toLowerCase().indexOf("win") >= 0;
		} else {
			isWindows = false;
		}
	}

	public Object execute(ExecutionEvent event) throws ExecutionException {
		if (!isWindows) {
			return null;
		}

		IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveMenuSelection(event);
		if (selection == null) {
			return null;
		}

		String containingDirectory = null;
		Object firstElement = selection.getFirstElement();

		if (firstElement instanceof IFile) {
			final IFile file = (IFile) firstElement;
			String fileName = file.getLocation().toOSString();
			int pos = fileName.lastIndexOf(File.separator);
			if (pos > 0) {
				fileName = fileName.substring(0, pos);
			}
			containingDirectory = fileName;

		} else if (firstElement instanceof IFolder) {
			final IFolder folder = (IFolder) firstElement;
			final IPath path = folder.getLocation();
			containingDirectory = path.toOSString();

		} else if (firstElement instanceof IProjectNature) {
			final IProjectNature project = (IProjectNature) firstElement;
			final IPath path = project.getProject().getLocation();
			containingDirectory = path.toOSString();

		} else if (firstElement instanceof ICompilationUnit) {
			final ICompilationUnit entry = (ICompilationUnit) firstElement;
			final IPath path = entry.getResource().getLocation();
			String fileName = path.toOSString();
			int pos = fileName.lastIndexOf(File.separator);
			if (pos > 0) {
				fileName = fileName.substring(0, pos);
			}
			containingDirectory = fileName;

		} else if (firstElement instanceof IPackageFragment) {
			final IPackageFragment entry = (IPackageFragment) firstElement;
			final IPath path = entry.getResource().getLocation();
			containingDirectory = path.toOSString();
		}

		if (containingDirectory != null) {
			try {
				Runtime.getRuntime().exec(new String[] { "explorer.exe", containingDirectory });
			} catch (IOException e) {}
		}
		return null;
	}
}
